package category

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"shopping/model"
	"shopping/service"
	"shopping/utils/api_helper"
	"shopping/utils/pagination"
	"shopping/utils/snowflake"
	"time"
)

// Controller 分类控制器
type Controller struct {
	categoryService *service.CategoryService
}

// NewCategoryController 实例化控制器
func NewCategoryController(s *service.CategoryService) *Controller {
	return &Controller{
		categoryService: s,
	}
}

// CreateCategory
// @Description 创建分类
// @receiver Controller
// @Summary 根据给定的参数创建分类
// @Tags Category
// @Accept json
// @Produce json
// @param Authorization header string true "Authorization header"
// @param CreateCategoryRequest body CreateCategoryRequest true "category information"
// @Success 200 {object} api_helper.Response
// @Failure 400 {object} api_helper.ErrorResponse
// @Router /category [post]
func (c *Controller) CreateCategory(g *gin.Context) {
	var req CreateCategoryRequest
	if err := g.ShouldBind(&req); err != nil {
		// 解析参数异常
		api_helper.HandleError(g, err)
		return
	}
	newCategory := model.NewCategory(req.Name, req.Desc)
	newCategory.CreateTime = time.Now()
	newCategory.Id = snowflake.GenID()
	err := c.categoryService.Create(newCategory)
	if err != nil {
		api_helper.HandleError(g, err)
		return
	}
	g.JSON(http.StatusCreated, api_helper.Response{
		Message: "category created",
	})
}

// BulkCreateCategory
// @Description 通过csv文件, 批量创建分类
// @receiver Controller
// @Summary 根据给定的csv文件, 批量创建分类
// @Tags Category
// @Accept multipart/form-data
// @Produce json
// @param Authorization header string true "Authorization header"
// @param file formData file true "分类信息csv文件"
// @Success 200 {object} api_helper.Response
// @Failure 400 {object} api_helper.ErrorResponse
// @Router /category/upload [post]
func (c *Controller) BulkCreateCategory(g *gin.Context) {
	fileHeader, err := g.FormFile("file")
	if err != nil {
		api_helper.HandleError(g, err)
		return
	}
	count, err := c.categoryService.BulkCreate(fileHeader)
	if err != nil {
		api_helper.HandleError(g, err)
		return
	}
	g.JSON(http.StatusOK, api_helper.Response{
		Message: fmt.Sprintf("'%s' upload! '%d' new categories created", fileHeader.Filename, count),
	})
}

// GetCategories 查询分类列表
// @receiver Controller
// @Summary 获得分类列表
// @Tags Category
// @Produce json
// @param page query int false "Page number"
// @param pageSize query int false "Page size"
// @Success 200 {object} pagination.Pages
// @Router /category [get]
func (c *Controller) GetCategories(g *gin.Context) {
	page := pagination.NewFormGinRequest(g, -1)
	page = c.categoryService.GetALl(page)
	g.JSON(http.StatusOK, page)
}
